package com.share.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.domain.Users;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.bean.BeanUtils;
import com.share.user.api.domain.UserInfo;
import com.share.user.api.domain.UserLogin;
import com.share.user.mapper.UserLoginLogMapper;
import com.share.user.mapper.UserInfoMapper;
import com.share.user.mapper.UsersMapper;
import com.share.user.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class IUserInfoServiceImpl implements IUserInfoService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserLoginLogMapper userLoginLogMapper;
    @Autowired
    private  UsersMapper usersMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public UserInfo wxLogin(String code) {
        String openId = null;
        try {
            //获取openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();

            log.info("【小程序授权】openId={}", openId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("微信登录失败");
        }

        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));
        if (null == userInfo) {
            userInfo = new UserInfo();
            userInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setWxOpenId(openId);
            userInfoMapper.insert(userInfo);
        }
        return userInfo;
    }

    @Override
    public void updateUserLogin(UserLogin userLogin) {
        Users users = new Users();
        BeanUtils.copyProperties(userLogin, users);
        usersMapper.updateById(users);
    }

    @Override
    public Boolean isFreeDeposit() {
        //微信支付分
        //https://pay.weixin.qq.com/wiki/doc/apiv3/payscore.php?chapter=18_1&index=2
        // 默认免押金，模拟实现
        Long userId = SecurityContextHolder.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        userInfo.setDepositStatus("1");
        userInfoMapper.updateById(userInfo);
        return true;
    }
}
